Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

295
Views
How to solve the "Cannot add class to undefined" Error?

I have a page that I am trying to remove an element of with this section of code

oldContainer = $('div.choose-location-options');
oldContainer.addClass('hidden');

I am using the $ selector because I read online and in this answer that $ is short for document.querySelector, this code is working fine.
During code review my colleagues have told me that they do not want us using the $ is not best practice because it looks like jquery. So I changed it to this.

oldContainer = document.querySelector('div.choose-location-options');
oldContainer.addClass('hidden');

However this code will return an error message saying that cannot add class to undefined
Running this code in the browser will also remove the oldContainer so I thought it was an issue with the page loading so I added an event listener to the code for a page load

window.addEventListener('load', (event) => {
   oldContainer = $('div.choose-location-options');
   oldContainer.addClass('hidden');
});

This also returns undefined So I know it is not a timing issue. Why is the shorthand $ working but not the document.querySelector?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!